﻿using System;
using System.Linq;

namespace OrmSmackdown.LinqToSql
{
    public class Aggregate : IAggregate
    {
        Linq2SqlDataContext _ctx;
        public Aggregate()
        {
            _ctx = new Linq2SqlDataContext();
        }

        public void InsertRecordsApproachOne(int recordsToInsert)
        {
            for (var idx = 0; idx < recordsToInsert; ++idx)
            {
                var perf = new Performance() { MilliSeconds = idx, Action = Constants.STR_AggregateCount, OrmName = "NHibernate" };
                _ctx.Performances.InsertOnSubmit(perf);
            }

            _ctx.SubmitChanges();

        }

        public void InsertRecordsApproachTwo(int recordsToInsert)
        {
            for (var idx = 0; idx < recordsToInsert; ++idx)
            {
                var perf = new Performance() { MilliSeconds = idx, Action = Constants.STR_AggregateCount, OrmName = "Linq2SQL" };
                _ctx.Performances.InsertOnSubmit(perf);
            }

            _ctx.SubmitChanges();
        }

        public int GetCountApproachOne()
        {
            return _ctx.Performances.Count(perf => perf.Action == Constants.STR_AggregateCount);
        }

        public int GetCountApproachTwo()
        {
            var query = (from perf
                          in _ctx.Performances
                         where perf.Action == Constants.STR_AggregateCount
                         select perf);

            return query.Count();
        }

        public int GetAverageApproachOne()
        {
            var query = _ctx.Performances.Where(perf => perf.Action == Constants.STR_AggregateCount).Select(perf => perf.MilliSeconds);
            return Convert.ToInt32(query.Average());
        }

        public int GetAverageApproachTwo()
        {
            var query = from perf
                          in _ctx.Performances
                         where perf.Action == Constants.STR_AggregateCount
                         select perf.MilliSeconds;

            return Convert.ToInt32(query.Average());
        }

        public void DeleteRecordsApproachOne()
        {
            AdoNet.Aggregate.ClearAggregateCounts();
        }

        public void DeleteRecordsApproachTwo()
        {
            AdoNet.Aggregate.ClearAggregateCounts();
        }

        public void Dispose()
        {
            _ctx.Dispose();
        }
    }
}
